const app = getApp()

export default function uploadFile(params) {
  const baseUrl = app.getConfig('baseUrl')
  const token = wx.getStorageSync('token')
  const {
    filePath,
    formData
  } = params
  const header = {
    "content-type": "multipart/form-data",
    "authority-token": token
  }
  if (app.isPrePro()) {
    // 预生产环境需要添加一个请求头
    header['x-current-env'] = 'Blue'
  }
  return new Promise((resovle, reject) => {
    if (!filePath) {
      return reject('filePath is null')
    }
    wx.uploadFile({
      url: `${baseUrl}/api/ljdp/attach/obs/upload.act`,
      filePath: filePath,
      header,
      name: 'file',
      formData,
      success(res) {
        const data = JSON.parse(res.data)
        if (data.code === 200) {
          return resovle(data)
        }
        switch (data.code) {
          case 200:
            return resolve(data)
          case 20019:
          case 20020:
          case 20021:
            app.toast('登录失效，请重新登录')
            const redirect = app.getCurRoute()
            setTimeout(() => {
              wx.redirectTo({
                url: `/pages/login/index?redirect=${encodeURIComponent(redirect)}`,
              })
            }, 1000)
            break
          default:
            return reject(res.data)
        }
      },
      fail(res) {
        return reject(res)
      }
    })
  })
}